package com.mpsc.current.unit;

import it.geosolutions.geoserver.rest.GeoServerRESTPublisher;
import it.geosolutions.geoserver.rest.GeoServerRESTReader;
import it.geosolutions.geoserver.rest.decoder.RESTCoverage;
import it.geosolutions.geoserver.rest.decoder.RESTCoverageStore;
import it.geosolutions.geoserver.rest.decoder.RESTDataStoreList;
import org.apache.commons.httpclient.NameValuePair;

import java.io.File;
import java.net.MalformedURLException;
import java.net.URI;
import java.util.List;

public class GeoServerUtil {

    static final String geoserverUrl = "http://localhost:8080/geoserver";
    static final String geoserverUsername = "admin";
    static final String geoserverPassword = "geoserver";

    /**
     * geoserver 发布 .tif 文件
     *
     * @param tifFile   tif文件绝对路径
     * @param workspace 工作空间
     * @param storeName
     */
    public static void releaseGeoTiffFile(String tifFile, String workspace, String storeName) throws Exception {

        GeoServerRESTPublisher serverPublisher = new GeoServerRESTPublisher(geoserverUrl, geoserverUsername, geoserverPassword);
        GeoServerRESTReader serverReader = new GeoServerRESTReader(geoserverUrl, geoserverUsername, geoserverPassword);

        String coverageName = storeName;
        File geotiff = new File(tifFile);

        //workspace是否存在，不存在则新建。
        List<String> workspacesList = serverReader.getWorkspaceNames();
        boolean wsNull = !workspacesList.contains(workspace);
        if (wsNull) {
            serverPublisher.createWorkspace(workspace);
        }
        //store是否存在，不存在则新建并发布数据。
        RESTDataStoreList datastoresList = serverReader.getDatastores(workspace);
        List<String> datastoreNameList = datastoresList.getNames();
        boolean storeNull = !datastoreNameList.contains(storeName);
        if (storeNull) {
            boolean result = serverPublisher.publishGeoTIFF(workspace, storeName, coverageName, geotiff);
            System.out.println("数据发布是否成功：" + result);
        } else {
            System.out.println("数据已经发布过了，不能重复发布！");
        }
    }

    /**
     * 删除已发布的 .tif 文件
     *
     * @param workspace
     * @param storeName
     */
    public static void deleteGeoTiffFile(String workspace, String storeName) throws MalformedURLException {

        GeoServerRESTPublisher serverPublisher = new GeoServerRESTPublisher(geoserverUrl, geoserverUsername, geoserverPassword);
        GeoServerRESTReader serverReader = new GeoServerRESTReader(geoserverUrl, geoserverUsername, geoserverPassword);

        String coverageName = storeName;

        // 测试coveragestore是否存在
        boolean coveragestoreNull = serverReader.existsCoveragestore(workspace, storeName);
        System.out.println("coveragestore是否存在：" + coveragestoreNull);

        // 测试coverage是否存在
        boolean coverageNull = serverReader.existsCoverage(workspace, storeName, coverageName);
        System.out.println("coverage是否存在：" + coverageNull);
        // 获取coverage
        if (coverageNull) {
            RESTCoverage coverage = serverReader.getCoverage(workspace, storeName, coverageName);
            coverage.getCRS();
            coverage.getSRS();
            //删除coverage
            boolean coverageResult = serverPublisher.unpublishCoverage(workspace, storeName, coverageName);
            System.out.println("coverage删除成功：" + coverageResult);
        }

        // 测试coveragestore是否存在
        boolean coveragestoreNull2 = serverReader.existsCoveragestore(workspace, storeName);
        System.out.println("coveragestore是否存在：" + coveragestoreNull2);

        if (coveragestoreNull2) {
            //获取coverageStore
            RESTCoverageStore coverageStore = serverReader.getCoverageStore(workspace, storeName);
            //删除coveragestore
            boolean coveragestoreResult = serverPublisher.removeCoverageStore(workspace, storeName, true);
            System.out.println("coveragestore删除成功：" + coveragestoreResult);
        }
    }


    /**
     * geoserver 发布 shp 文件
     *
     * @param zipFilepath   zip文件绝对路径
     * @param workspace     工作空间
     * @param datastoreName 必须和zip压缩包的名称一致
     * @param layerName     必须和压缩包里面shp的名称一致
     */
    public static void releaseGeoShpFile(String zipFilepath, String workspace, String datastoreName, String layerName) throws Exception {
        GeoServerRESTPublisher serverPublisher = new GeoServerRESTPublisher(geoserverUrl, geoserverUsername, geoserverPassword);
        GeoServerRESTReader serverReader = new GeoServerRESTReader(geoserverUrl, geoserverUsername, geoserverPassword);

        //发布zip格式的shp数据(直接把shp等相关数据压缩成zip格式，中间不要加文件夹)
        File zipFile = new File(zipFilepath);
        String srs = "EPSG:4326";

        //workspace是否存在，不存在则新建。
        List<String> workspacesList = serverReader.getWorkspaceNames();
        boolean wsNull = !workspacesList.contains(workspace);
        if (wsNull) {
            serverPublisher.createWorkspace(workspace);
        }

        //datastore是否存在，不存在则新建并发布数据。
        RESTDataStoreList datastoresList = serverReader.getDatastores(workspace);
        List<String> datastoreNameList = datastoresList.getNames();
        boolean storeNull = !datastoreNameList.contains(datastoreName);
        if (storeNull) {
            boolean result = serverPublisher.publishShp(workspace, datastoreName, layerName, zipFile, srs);
            System.out.println("数据发布是否成功：" + result);
        } else {
            System.out.println("数据已经发布过了，不能重复发布！");
        }
    }

    /**
     * geoserver 发布 shp 文件(带style)
     *
     * @param zipFilepath   zip文件绝对路径
     * @param workspace     工作空间
     * @param datastoreName 必须和zip压缩包的名称一致
     * @param layerName     必须和压缩包里面shp的名称一致
     */
    public static void releaseGeoShpStyleFile(String zipFilepath, String workspace, String datastoreName, String layerName) throws Exception {
        GeoServerRESTPublisher serverPublisher = new GeoServerRESTPublisher(geoserverUrl, geoserverUsername, geoserverPassword);
        GeoServerRESTReader serverReader = new GeoServerRESTReader(geoserverUrl, geoserverUsername, geoserverPassword);

        //发布zip格式的shp数据(直接把shp等相关数据压缩成zip格式，中间不要加文件夹)
        File zipFile = new File(zipFilepath);      //shp数据zip压缩包
        URI uri = zipFile.toURI();
        NameValuePair nameValuePair = new NameValuePair("charset", "UTF-8");
        NameValuePair[] nameValuePairsArr = new NameValuePair[1];   //字符串等相关配置
        nameValuePairsArr[0] = nameValuePair;
        String srs = "EPSG:4326";                   //shp数据坐标系
        String style = "restteststyle";             //shp数据样式

        //workspace是否存在，不存在则新建。
        List<String> workspacesList = serverReader.getWorkspaceNames();
        boolean wsNull = !workspacesList.contains(workspace);
        if (wsNull) {
            serverPublisher.createWorkspace(workspace);
        }

        //datastore是否存在，不存在则新建并发布数据。
        RESTDataStoreList datastoresList = serverReader.getDatastores(workspace);
        List<String> datastoreNameList = datastoresList.getNames();
        boolean storeNull = !datastoreNameList.contains(datastoreName);
        if (storeNull) {
            boolean result = serverPublisher.publishShp(workspace, datastoreName, nameValuePairsArr,
                    layerName, GeoServerRESTPublisher.UploadMethod.FILE, uri, srs, style);
            System.out.println("数据发布是否成功：" + result);
        } else {
            System.out.println("数据已经发布过了，不能重复发布！");
        }
    }

    /**
     * geoserver 删除已发布的 shp 文件
     *
     * @param workspace     工作空间
     * @param datastoreName 要删除的datastore
     * @param layerName     要删除的layer
     */
    public static void deleteGeoShpStyleFile(String workspace, String datastoreName, String layerName) throws Exception {
        GeoServerRESTPublisher serverPublisher = new GeoServerRESTPublisher(geoserverUrl, geoserverUsername, geoserverPassword);
        GeoServerRESTReader serverReader = new GeoServerRESTReader(geoserverUrl, geoserverUsername, geoserverPassword);


        // 测试datastore是否存在
        boolean datastoreNull = serverReader.existsDatastore(workspace, datastoreName);
        System.out.println("datastore是否存在：" + datastoreNull);

        //测试featuretype是否存在
        boolean featureTypeNull = serverReader.existsFeatureType(workspace, datastoreName, layerName);
        System.out.println("featureType是否存在：" + featureTypeNull);


        //删除featuretype
        boolean deleteResult = serverPublisher.unpublishFeatureType(workspace, datastoreName, layerName);
        System.out.println("删除FeatureType是否成功:" + deleteResult);

        // 删除datastore
        boolean deleteResult2 = serverPublisher.removeDatastore(workspace, datastoreName, false);
        System.out.println("删除Datastore是否成功：" + deleteResult2);


        // 测试featuretype是否存在
        boolean featureTypeNull2 = serverReader.existsFeatureType(workspace, datastoreName, layerName);
        System.out.println("featureType是否存在：" + featureTypeNull2);

        // 测试datastore是否存在
        boolean datastoreNull2 = serverReader.existsDatastore(workspace, datastoreName);
        System.out.println("datastore是否存在：" + datastoreNull2);
    }

    /**
     * geoserver 发布 sld 样式
     *
     * @param sldFilepath sld文件绝对路径
     * @param workspace   工作空间
     */
    public static void releaseGeoSldFile(String sldFilepath, String workspace) throws Exception {
        GeoServerRESTPublisher serverPublisher = new GeoServerRESTPublisher(geoserverUrl, geoserverUsername, geoserverPassword);
        GeoServerRESTReader serverReader = new GeoServerRESTReader(geoserverUrl, geoserverUsername, geoserverPassword);

        File sldFile = new File(sldFilepath); //默认发表的样式名等于文件名
        int index = sldFile.getName().lastIndexOf(".");
        String styleName = sldFile.getName().substring(0, index);
        System.out.print(styleName);

        //workspace是否存在，不存在则新建。
        List<String> workspacesList = serverReader.getWorkspaceNames();
        boolean wsNull = !workspacesList.contains(workspace);
        if (wsNull) {
            serverPublisher.createWorkspace(workspace);
        }

        //样式是否存在
        boolean styleFlag = serverReader.existsStyle(workspace, styleName);
        if (styleFlag) {
            System.out.println(styleName + "样式已经存在了！");
        } else {
            boolean sldPublishResult = serverPublisher.publishStyleInWorkspace(workspace, sldFile);
            if (sldPublishResult) {
                System.out.println(styleName + "样式发布成功！");
            } else {
                System.out.println(styleName + "样式发布失败！");
            }
        }
    }

    /**
     * geoserver 删除sld样式
     *
     * @param workspace 工作空间
     * @param styleName 样式名称
     */
    public static void deleteGeoSldFile(String workspace, String styleName) throws Exception {
        GeoServerRESTPublisher geoServerRESTPublisher = new GeoServerRESTPublisher(geoserverUrl, geoserverUsername, geoserverPassword);
        GeoServerRESTReader geoServerRESTReader = new GeoServerRESTReader(geoserverUrl, geoserverUsername, geoserverPassword);
        boolean workspaceExist = geoServerRESTReader.existsWorkspace(workspace);
        if (!workspaceExist) {
            System.out.println(workspace + "工作空间不存在！");
            return;
        }
        boolean styleExist = geoServerRESTReader.existsStyle(workspace, styleName);
        if (styleExist) {
            boolean styleRemoveResult = geoServerRESTPublisher.removeStyleInWorkspace(workspace, styleName, true);
            if (styleRemoveResult) {
                System.out.println(workspace + "工作空间下的" + styleName + "样式删除成功！");
            } else {
                System.out.println(workspace + "工作空间下的" + styleName + "样式删除失败！");
            }
        } else {
            System.out.println("要删除的样式不存在！");
        }
    }
}
